package com.iotproject.studyservice.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.iotproject.servicebase.exceptionhandler.GlobalException;
import com.iotproject.studyservice.entity.StudyGrade;
import com.iotproject.studyservice.entity.StudyWord;
import com.iotproject.studyservice.entity.excel.StudyWordData;
import com.iotproject.studyservice.service.StudyGradeService;
import com.iotproject.studyservice.service.StudyWordService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.util.StringUtils;

public class StudyWordExcelListener extends AnalysisEventListener<StudyWordData> {

    StudyWordService studyWordService;
    StudyGradeService studyGradeService;

    public StudyWordExcelListener() {
    }

    public StudyWordExcelListener(StudyWordService studyWordService, StudyGradeService studyGradeService) {
        this.studyWordService = studyWordService;
        this.studyGradeService = studyGradeService;
    }

    @Override
    public void invoke(StudyWordData studyWordData, AnalysisContext analysisContext) {
        if (studyWordData == null) {
            throw new GlobalException(20001, "文件数据为空");
        }
        String name = studyWordData.getName();
        String audio = studyWordData.getAudio();
        String explanation = studyWordData.getExplanation();
        String gradeName = studyWordData.getGrade();
        String example = studyWordData.getExample();
        QueryWrapper<StudyGrade> studyGradeQueryWrapper = new QueryWrapper<>();
        studyGradeQueryWrapper.eq("name", gradeName);
        StudyGrade studyGrade = studyGradeService.getOne(studyGradeQueryWrapper);
        //这里认为excel表里的grade在study_grade表存在
        String grade = studyGrade.getId();
        StudyWord studyWord = existWord(studyWordService, name, grade);
        if (studyWord == null) {
            if(!StringUtils.isEmpty(audio)) {//在音标开始结束位置添加[]
                audio = "[" + audio + "]";
            }
            if (StringUtils.isEmpty(example)) {//例句为空
                example = "无";
            }
            studyWord = new StudyWord();
            studyWord.setName(name);
            studyWord.setAudio(audio);
            studyWord.setExplanation(explanation);
            studyWord.setExample(example);
            studyWord.setGrade(grade);
            studyWordService.save(studyWord);
        }

    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }

    //判断单词是否重复
    //可以根据 单词名称name 单词类别grade判断 判断
    public StudyWord existWord(StudyWordService studyWordService, String name, String grade) {
        QueryWrapper<StudyWord> studyWordQueryWrapper = new QueryWrapper<>();
        studyWordQueryWrapper.eq("name", name);
        studyWordQueryWrapper.eq("grade", grade);
        StudyWord studyWord = studyWordService.getOne(studyWordQueryWrapper);
        return studyWord;
    }



}
